﻿using LLog.Web.Models;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LLog.Web
{
    public class DbClient
    {
        public static SqlSugarClient Create()
        {
            return new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = "FileName=LLog.db",
                DbType = DbType.Sqlite,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            });
        }
        public static void InitDataBase()
        {
            using (var db = Create())
            {
                var initTable = false;
                if (db.DbMaintenance.IsAnyTable(nameof(Migration)))
                {
                    var updates = MigrationConfig.Instance.GetUpdates();
                    var versions = updates.Select(x => x.Version).ToArray();
                    var hasNoMigration = db.Queryable<Migration>().Any(x => !versions.Contains(x.Version));
                    if (hasNoMigration)
                        initTable = true;
                }
                else
                {
                    initTable = true;
                }
                if (initTable)
                {
                    db.CodeFirst.BackupTable().InitTables(typeof(Log), typeof(Migration));
                }
               
            }
        }
    }
}
